package net.huashitong.service.user;

import net.huashitong.mapper.user.SsUserLoginTokenMapper;
import net.huashitong.ssydt.security.entity.SsUserLoginToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @author shaoxian.zhong
 * @create 2018-06-25 17:59
 */
@Transactional
@Service
public class SsUserLoginTokenServiceImpl implements SsUserLoginTokenService {
    @Autowired
    private SsUserLoginTokenMapper mapper;
    @Autowired
    private UserRedisService userRedisService;

    @Override
    public SsUserLoginToken getByUserId(String userId) {
        return mapper.getByUserId(userId);
    }

    @Override
    public void update(SsUserLoginToken ssUserLoginToken) {
        mapper.update(ssUserLoginToken);
    }

    @Override
    public SsUserLoginToken login(String userId) {
        SsUserLoginToken ssUserLoginToken = getByUserId(userId);
        if (ssUserLoginToken == null) {
            ssUserLoginToken = new SsUserLoginToken();
            ssUserLoginToken.setUserId(userId);
            ssUserLoginToken.setToken(UUID.randomUUID().toString().trim().replaceAll("-", ""));
            ssUserLoginToken.setExpiration(System.currentTimeMillis() + 1296000000L);//15天后过期 1000*60*60*24*15 = 1296000000
            save(ssUserLoginToken);
        } else {
            ssUserLoginToken.setToken(UUID.randomUUID().toString().trim().replaceAll("-", ""));
            ssUserLoginToken.setExpiration(System.currentTimeMillis() + 1296000000L);//15天后过期 1000*60*60*24*15 = 1296000000
            update(ssUserLoginToken);
        }
        userRedisService.setToken(ssUserLoginToken.getUserId(), ssUserLoginToken.getToken());
        return ssUserLoginToken;
    }

    public void save(SsUserLoginToken ssUserLoginToken) {
        mapper.save(ssUserLoginToken);
    }

}
